<template>
  <el-tree-select
    v-model="selectedIds"
    multiple
    :data="treeData"
    :props="treeProps"
    :render-after-expand="false"
    :disabled="inputDisabled"
    :placeholder="placeholder"
    :default-expanded-keys="expandedData"
    :expand-on-click-node="false"
    show-checkbox
    filterable
    check-on-click-node
    style="width: 100%"
  />
</template>

<script setup>
import { ref, watch, onMounted, inject } from 'vue';
import { useDisabled } from 'element-plus';
import { getOrganization } from '@/utils/system';
import tool from "@/utils/tool";

const emit = defineEmits(['change'])
const props = defineProps({
  prop: String,
  placeholder: {
    type: String,
    default: '--请选择--'
  },
});
const formData = inject('formData');

const initializing = ref(false);
const selectedIds = ref([]);
const expandedData = ref([]);
const inputDisabled = useDisabled();
const treeData = ref([]);
const treeProps = ref({
  value: 'id',
  label: 'text',
  children: 'children'
});

const loadTree = async() => {
  treeData.value = await getOrganization();
  tool.walkTree({children: treeData.value}, (node) => {
    node.value = node.id;
    node.label = node.text;
  });

  if (treeData.value && treeData.value.length === 1) {
    expandedData.value = [treeData.value[0].id];
  }
};

watch(() => selectedIds.value, (newVal) => {
  if (initializing.value) return;

  initializing.value = true;
  formData.value[props.prop] = newVal.join(',');
  setTimeout(() => initializing.value = false, 500);
});

watch(() => formData.value[props.prop], (newVal) => {
  if (initializing.value) return;

  initializing.value = true;
  selectedIds.value = newVal ? newVal.split(',') : [];
  emit('change');
  setTimeout(() => initializing.value = false, 500);
});

onMounted(() => {
  selectedIds.value =  formData.value[props.prop] ? formData.value[props.prop].split(',') : [];
  loadTree();
});
</script>